﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Common;
using System.Collections;
using System.Configuration;
using System.Reflection;
using DTC.Models;
using System.Threading;

namespace DTC
{
    public partial class FrmDisplay : UIBase
    {
    //    FIO01 m_io;
    //    Hashtable htStateImage = new Hashtable()
        ProductMachine _cellMachine;//机器的抽象表示
        public string CellName { get; set; }
        public string ModelName { get; set; }
        public DateTime dtimeClear { get; set; }
        //     System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer(); //用于检测IO状态
        System.Windows.Forms.Timer tmrUpdate = new System.Windows.Forms.Timer();
        #region 报表属性集合
        public string SummaryPassCount
        {
            get
            {
                return listView1.Items[0].SubItems[1].Text;
            }
            set
            {
                listView1.Items[0].SubItems[1].Text = value;
            }
        }
        public string SummaryPassRate
        {
            get
            {
                return listView1.Items[0].SubItems[2].Text;
            }
            set
            {
                listView1.Items[0].SubItems[2].Text = value;
            }
        }
        public string SummaryFailCount
        {
            get
            {
                return listView1.Items[1].SubItems[1].Text;
            }
            set
            {
                listView1.Items[1].SubItems[1].Text = value;
            }
        }
        public string SummaryFailRate
        {
            get
            {
                return listView1.Items[1].SubItems[2].Text;
            }
            set
            {
                listView1.Items[1].SubItems[2].Text = value;
            }
        }
        public string SummaryTotalQty
        {
            get
            {
                return listView1.Items[2].SubItems[1].Text;
            }
            set
            {
                listView1.Items[2].SubItems[1].Text = value;
            }
        }

        #endregion

        public FrmDisplay()
        {
            InitializeComponent();
        }

        private void FrmDisplay_Load(object sender, EventArgs e)
        {

            _cellMachine = new ProductMachine(CellName);//备注：需要Cellname判断是不是存在或为空
            _cellMachine.ShowMsg = ShowMsg;
            _cellMachine.className = "TMC01";
            _cellMachine.ModelName = ModelName;
            IOCardInitial();
            _cellMachine.ShowTestSpan = ShowTestSpan;
            this.edtDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            this.edtLot.Text = ConfigurationManager.AppSettings["MO"];
            this.edtOper.Text = ConfigurationManager.AppSettings["Operator"];
            this.edtPName.Text = ModelName;
            tmrUpdate.Interval = 1000;
            tmrUpdate.Tick += tmrUpdate_Tick;
            tmrUpdate.Start();
            this.Top = 0;
            this.Left = 0;
            this.Width = Screen.PrimaryScreen.WorkingArea.Width;
            this.Height = Screen.PrimaryScreen.WorkingArea.Height;

            //设定初始统计时间,为软件开启的时间
            dtimeClear = DateTime.Now;
            try
            {
                BLL.Test_DatasManager.CreateDataBase();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(FrmDisplay), ex);
            }
        }

        void tmrUpdate_Tick(object sender, EventArgs e)
        {
            //  throw new NotImplementedException();
            edtCurrentTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            edtDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            if (DateTime.Now.ToString("HH:mm:ss") == ConfigurationManager.AppSettings["ExportXlsxTime"])
            {
                Thread trd = new Thread(SaveReport);
                trd.IsBackground = true;
                trd.Start();
            }
        }

        private static void SaveReport()
        {
            try
            {
                DataTable dt = BLL.Test_DatasManager.GetTestDataTable(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                common.recordsaver.saveexcel(dt, DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(FrmDisplay), ex);
            }
        }
        private void SaveReport3000()
        {
            try
            {
                DateTime tempdtime = dtimeClear;
                dtimeClear = DateTime.Now;
                DataTable dt = BLL.Test_DatasManager.GetTestDataTable(tempdtime.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                common.recordsaver.saveexcel(dt, tempdtime.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(FrmDisplay), ex);
            }
        }

        private void ShowTestSpan(List<TestSpan> obj)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action<List<TestSpan>>(ShowTestSpan), new object[] { obj });
            }
            else
            {
                this.dataGridView1.DataSource = new BindingList<TestSpan>(new List<TestSpan>(obj));
                Changedgvx1Corlor();
            }
        }

        private void IOCardInitial()
        {
            try
            {
                PISO730.Instance.WriteBit(0, true);
                PISO730.Instance.AddReadObserver(StartTestProc);   
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, "开启IO卡成功");
                LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, Convert.ToString(PISO730.Instance.Read(),2));
            }
            catch (Exception ex)
            {
                ShowError(ex.Message + Environment.NewLine
                    + "IO Card 打开失败，请确认驱动安装和IO Card连接状态。");
            }
        }

        private void StartTestProc()
        {
            Thread trd = new Thread(testMain);
            trd.IsBackground = true;
            trd.Start();
        }
        private void testMain()
        {
     //       Common.CommonHelper.AllocConsole();
            try
            {
                try
                {   
                    if(ConsoleOpened)
                        Console.Clear();
                    Console.WriteLine("=============test main==============");
                }
                catch (Exception)
                {
                    
                 //   throw;
                }
                _cellMachine.Step();

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(FrmDisplay), ex);
                _cellMachine.ClearProducts();

            }
            //  Common.CommonHelper.FreeConsole();
        }

        public void ReSetState()
        {
            ResetState();
        }

        private void ShowMsg(string msg)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action<string>(ShowMsg), new object[] { msg });
                return;
            }
            LogHelper.WriteLog(MethodBase.GetCurrentMethod().DeclaringType, msg);
            this.SummaryFailCount = CountManager.TotalFailCount.ToString();
            this.SummaryPassCount = CountManager.TotalPassCount.ToString();
            SummaryTotalQty = CountManager.TotalCount.ToString();
            if (CountManager.TotalCount > 0)
            {
                SummaryFailRate = (CountManager.TotalFailCount * 1.0 / CountManager.TotalCount).ToString("P");
                SummaryPassRate = (CountManager.TotalPassCount * 1.0 / CountManager.TotalCount).ToString("P");         
            }
            //if (CountManager.TotalCount ==3000)
            //{
            //    StartNotify();
            //}
        }



        private void Changedgvx1Corlor()
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                string value = row.Cells["测试结果"].Value.ToString();
                if (value.ToUpper().Contains("PASS"))
                {
                    row.Cells["测试结果"].Style.BackColor = Color.LightGreen;
                }
                else if (value.ToUpper().Contains("FAIL"))
                {
                    row.Cells["测试结果"].Style.BackColor = Color.Red;
                }
                else
                {
                    row.Cells["测试结果"].Style.BackColor = Color.Gray;
                }
            }
        }

        public void ResetState()
        {
            //      DialogResult dr = ShowQuestion("真的要清空数据,恢复到初始状态吗？");
            //       if (dr == DialogResult.Yes)
            {
                //   _cellMachine.ClearProducts();
                CountManager.ClearCounts();
                SummaryPassCount = "0";
                SummaryPassRate = "100%";
                SummaryFailCount = "0";
                SummaryFailRate = "0%";
                SummaryTotalQty = "0";
                dataGridView1.Rows.Clear();
                ShowMsg("清空操作被执行");
            }

        }

        private void dataGridViewX1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
            //   e.
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (ShowQuestion("是否真的要关闭数据采集软件？") == DialogResult.Yes)
            {
                Application.Exit();
                System.Environment.Exit(0);
            }

        }
        private void button4_Click(object sender, EventArgs e)
        {
            ResetState();
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            this.btnStop.Enabled = true;
            this.btnStart.Enabled = false;
            this.btnExit.Enabled = false;
            PISO730.Instance.Start();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            this.btnStop.Enabled = false;
            this.btnStart.Enabled = true;
            this.btnExit.Enabled = true;
            PISO730.Instance.Stop();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void label25_Click(object sender, EventArgs e)
        {
            testMain();
        }

        private void StartNotify()
        {
            WarnPulse();
            Thread trd = new Thread(SaveReport3000);
            trd.IsBackground = true;
            trd.Start();
            ResetState();
            FrmMessage frmMsg = new FrmMessage() { disp = this };
            frmMsg.Show(this);
        }
        private void WarnPulse()
        {
            Common.PISO730.Instance.WriteBit(ushort.Parse(ConfigurationManager.AppSettings["IOWarn"]), true);
            Delay(500);
            Common.PISO730.Instance.WriteBit(ushort.Parse(ConfigurationManager.AppSettings["IOWarn"]),false);
        }

        private static void Delay(int span)
        {
            int iStart = Environment.TickCount;
            do
            {
                Thread.Sleep(10);
                Application.DoEvents();
            } while (Environment.TickCount - iStart < span);
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            FrmHistory his = new FrmHistory();
            his.Show(this);
        }

        private void FrmDisplay_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                Common.PISO730.Instance.Write(0x00);
                LogHelper.WriteLog(typeof(FrmDisplay), "Form Closed");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(FrmDisplay), ex);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartNotify();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }
        bool ConsoleOpened = false;
        private void 打开关闭控制台ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!ConsoleOpened)
            {
                Common.CommonHelper.InitialConsole("调试窗口");
                ConsoleOpened = true;
            }
            else
            {
                Common.CommonHelper.FreeConsole();
                ConsoleOpened = false;
            }
        }

        private void 单步调试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            testMain();
        }

        private void edtCurrentTime_TextChanged(object sender, EventArgs e)
        {

        }

        private void edtOper_TextChanged(object sender, EventArgs e)
        {

        }

        private void edtDate_TextChanged(object sender, EventArgs e)
        {

        }

        private void edtLot_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            StartNotify();
        }

        private void iO状态ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmIOTrace frm = new FrmIOTrace();
            frm.Show();
        }
    }
}
